package com.rongke.web.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.Optionsymbol;
import com.rongke.model.PageModel;
import com.rongke.model.User;
import com.rongke.model.UserOptionsymbol;
import com.rongke.service.OptionsymbolService;
import com.rongke.service.UserOptionsymbolService;
import com.rongke.service.UserService;
import com.rongke.utils.RandomUtils;
import com.rongke.web.thirdapi.UdSymbol;
import com.rongke.web.thirdapi.model.PriceLineRequest;
import com.rongke.web.thirdapi.model.QuoteOptionRequest;
import com.rongke.web.yiyuan.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @OptionsymbolController
 * @股票(后台)Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/optionsymbol")
@Transactional
@CrossOrigin
public class OptionsymbolController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private OptionsymbolService optionsymbolService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserOptionsymbolService userOptionsymbolService;
    /**
     * @添加股票(后台)
     * @param optionsymbol
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addOptionsymbol(@RequestBody Optionsymbol optionsymbol){
        log.debug("添加股票(后台)");
        optionsymbolService.insert(optionsymbol);
        return JsonResp.ok(optionsymbol);
    }
    @RequestMapping(value="/addAll", method = RequestMethod.GET)
    public JsonResp addOptionsymbols(){
        log.debug("添加所有期权");
        UdSymbol udSymbol = new UdSymbol();
        String optionSymbolCollection = udSymbol.getOptionSymbolCollection();
        JSONObject jsonObject = JSONObject.parseObject(optionSymbolCollection);
        JSONArray optionsymbolcollection = jsonObject.getJSONArray("optionsymbolcollection");
        System.out.println(11111+optionsymbolcollection.toJSONString());
        List<Optionsymbol> optionsymbols = JSONArray.parseArray(optionsymbolcollection.toJSONString(), Optionsymbol.class);
//        List<Optionsymbol> optionsymbols = JSONArray.parseArray(optionSymbolCollection, Optionsymbol.class);
        for (Optionsymbol optionsymbol:
             optionsymbols) {
            optionsymbol.setCreateDatetime(new Date());
        }
        boolean b = optionsymbolService.insertBatch(optionsymbols);
        if (b)
        return JsonResp.ok("导入成功");
        return JsonResp.fa("导入失败");
    }

    /**
     * @备注：添加或删除自选期权
     * @param mdOptionId 期权id
     * @param type 操作类型 0-添加 1-删除
     *
     * @return
     */
    @RequestMapping("/addCollect")
    public JsonResp addCollect(Long mdOptionId,int type){
        User loginUser = userService.findLoginUser();
        Long userId = loginUser.getId();
        EntityWrapper<UserOptionsymbol> userOptionsymbolEntityWrapper = new EntityWrapper<>();
        userOptionsymbolEntityWrapper.eq("user_id",userId);
        userOptionsymbolEntityWrapper.eq("optionsymbol_id",mdOptionId);
        UserOptionsymbol selectUserOptionsymbol = userOptionsymbolService.selectOne(userOptionsymbolEntityWrapper);
        if (type==0){
            if (selectUserOptionsymbol!=null){
                return JsonResp.fa("不能重复添加期权信息");
            }
            UserOptionsymbol userOptionsymbol = new UserOptionsymbol();
            userOptionsymbol.setCreateDatetime(new Date());
            userOptionsymbol.setOptionsymbolId(mdOptionId);
            userOptionsymbol.setUserId(loginUser.getId());
            boolean b = userOptionsymbolService.insert(userOptionsymbol);
            if (b){
                return JsonResp.ok("添加成功");
            }
        }
        if (type==1){
            if (selectUserOptionsymbol!=null){
                selectUserOptionsymbol.setStatus(1);
                selectUserOptionsymbol.setUpdateDatetime(new Date());
                boolean b = userOptionsymbolService.updateById(selectUserOptionsymbol);
                if (b){
                    return JsonResp.ok("删除成功");
                }
            }
        }
        return JsonResp.fa("操作失败");
    }


    /**
     * @修改股票(后台)
     * @param optionsymbol
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateOptionsymbol(@RequestBody Optionsymbol optionsymbol){
        log.debug("修改股票(后台)");
        optionsymbolService.updateById(optionsymbol);
        return JsonResp.ok(optionsymbol);
    }
    /**
     * @根据id查找股票(后台)
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectOptionsymbol(Long id){
        log.debug("查找股票(后台)");
        Optionsymbol optionsymbol = optionsymbolService.selectById(id);
        return JsonResp.ok(optionsymbol);
    }

    /**
     * @备注：分页查询自选期权信息
     * @return
     */
    @RequestMapping(value = "/userOptionsymbolsPage",method = RequestMethod.GET)
    public JsonResp selectUserOptionsymbols(int pageNum){
        User loginUser = userService.findLoginUser();
        EntityWrapper<UserOptionsymbol> userOptionsymbolEntityWrapper = new EntityWrapper<>();
        userOptionsymbolEntityWrapper.eq("user_Id",loginUser.getId());
        userOptionsymbolEntityWrapper.orderBy("createDatetime",false);
        userOptionsymbolEntityWrapper.eq("status",0);
        List<UserOptionsymbol> userOptionsymbols = userOptionsymbolService.selectList(userOptionsymbolEntityWrapper);
        EntityWrapper<Optionsymbol> optionsymbolEntityWrapper = new EntityWrapper<>();
        List<Long> mdOptionIds = new ArrayList<>();
        for (UserOptionsymbol userOptionsymbol:
             userOptionsymbols) {
            mdOptionIds.add(userOptionsymbol.getOptionsymbolId());
        }
        if (mdOptionIds.size()>0){
            optionsymbolEntityWrapper.in("md_option_id",mdOptionIds);
            optionsymbolEntityWrapper.eq("status",1);
            PageModel<Optionsymbol> optionsymbols = getOptionsymbols(pageNum, optionsymbolEntityWrapper);


            return JsonResp.ok(optionsymbols);
        }
        return JsonResp.ok("没有自选信息");
    }


    /**
     * @备注:分页查询发布中的期权信息
     * @param pageNum
     * @return JsonResp
     */
    @RequestMapping(value = "/selectPage",method = RequestMethod.GET)
    public JsonResp selectPage(int pageNum){
        log.debug("分页查询发布的期权信息");

        EntityWrapper<Optionsymbol> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("status",1);
        entityWrapper.orderBy("createDatetime",false);
        PageModel<Optionsymbol> pageModel = getOptionsymbols(pageNum, entityWrapper);


        return JsonResp.ok(pageModel);
    }


    /*
        *@分页查询推荐期权信息
     */
    @RequestMapping(value = "/selectCommentPage",method = RequestMethod.GET)
    public JsonResp selectComment(int pageNum){
        log.debug("分页查询推荐期权信息");

        EntityWrapper<Optionsymbol> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("commend",1);
        entityWrapper.eq("status",1);
        entityWrapper.orderBy("createDatetime",false);
        PageModel<Optionsymbol> pageModel = getOptionsymbols(pageNum, entityWrapper);


        return JsonResp.ok(pageModel);
    }

    /*
    *分页查询期权信息
     */
    public PageModel<Optionsymbol> getOptionsymbols(int pageNum, EntityWrapper<Optionsymbol> entityWrapper){
        Page<Optionsymbol> page = new Page(pageNum-1,10);
        Page<Optionsymbol> optionsymbolPage = optionsymbolService.selectPage(page,entityWrapper);
        List<Optionsymbol> optionsymbols = optionsymbolPage.getRecords();
        UdSymbol udSymbol = new UdSymbol();
        if (optionsymbols.size()>0) {
            List<QuoteOptionRequest> quoteOptionRequests = new ArrayList<>();
            for (Optionsymbol optionsymbol :
                    optionsymbols) {
                PriceLineRequest priceLineRequest= new PriceLineRequest();
                priceLineRequest.setExch_id(optionsymbol.getExchId());
                priceLineRequest.setReq_id(RandomUtils.randomNumber(6).toString());
                priceLineRequest.setSymbol(optionsymbol.getUnderlying());
                String priceLine = udSymbol.getPriceLine(priceLineRequest);
//                System.out.println("最新价格:"+priceLine);
                if (priceLine!=null&& !StringUtils.isEmpty(priceLine)){
                    JSONObject priceLineJson = JSONObject.parseObject(priceLine);
                    JSONArray priceJson = priceLineJson.getJSONArray("priceline");
//                priceJson.getJSONArray()
//                JSONArray objects = JSONArray.parseArray(priceJson.toJSONString());
//                String[] prices = (String[])objects.get(0);
                    float prePrice = Float.parseFloat(priceJson.getJSONArray(0).get(3).toString());
                    float price = Float.parseFloat(priceJson.getJSONArray(0).get(2).toString());
                    Float chg = (price-prePrice)/prePrice*100;
                    optionsymbol.setChg(chg);
                }
                if (optionsymbol.getTimeSpan()/60/60/24%7==0){
                    if (optionsymbol.getTimeSpan()/60/60/24/7%30==0){
                        optionsymbol.setStrTime(optionsymbol.getTimeSpan()/60/60/24/7/30+"月");
                    }
                    optionsymbol.setStrTime(optionsymbol.getTimeSpan()/60/60/24/7+"周");
                }else {
                    optionsymbol.setStrTime(optionsymbol.getTimeSpan()/60/60/24+"天");
                }

                QuoteOptionRequest quoteOptionRequest = new QuoteOptionRequest();
                quoteOptionRequest.setReq_id(Integer.parseInt(RandomUtils.randomString(5)));
                quoteOptionRequest.setMd_option_id(optionsymbol.getMdOptionId());
                quoteOptionRequests.add(quoteOptionRequest);
            }

            String quoteOption = udSymbol.getQuoteOption(quoteOptionRequests);
            System.out.println(quoteOption);
            JSONArray objects = JSONArray.parseArray(quoteOption);
            for (int i = 0; i < objects.size(); i++) {
                JSONObject object = objects.getJSONObject(i);
                Integer mdOptionId = object.getInteger("md_option_id");
                for (Optionsymbol optionsymbol :
                        optionsymbols) {
                    if (optionsymbol.getMdOptionId() == mdOptionId) {
                        optionsymbol.setPrice(object.getFloat("price"));
                        optionsymbol.setPremiumRate(object.getFloat("premium_rate"));
                    }
                }
            }
        }
        PageModel<Optionsymbol> pageModel = new PageModel<>();
        pageModel.setPages(optionsymbolPage.getPages());
        pageModel.setTotal(optionsymbolPage.getTotal());
        pageModel.setContent(optionsymbols);
        return pageModel;
    }
}
